package com.is2.patchinglife.activity;

import com.is2.patchinglife.manager.ContentManager;
import com.is2.patchinglife.manager.LocalDataManager;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class TrophyService extends Service {
	
	// FREQUENCY PARAMETERS
	private Thread myThread;
	private boolean runThread = true;		// flag [stop service?]
	private boolean lastTrophies = true;	// flag [are there any last trophies?]
	private int WAIT = 15*60*1000; 			// sleep time [ms]
	private int WAIT_OFFSET = 2*60*1000; 	// sleep offset time [ms]
	
	// TROPHY PARAMETERS
	private final String countSMS = "countSMS_01";
	private final int nSMS = 30;
	private final String countContacts = "countContacts_01";
	private final int nContacts = 30;
	
	
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);

		myThread = new Thread(new ServiceWorker());
		myThread.start();
		
		return START_NOT_STICKY;
	}

	
	class ServiceWorker implements Runnable{
		
		public void run(){

			while(runThread){
				try {
					// check last trophies
					if(lastTrophies){
						
						Thread.sleep(WAIT_OFFSET);	// check offset
						
						lastTrophies = false;		// reset flag
						
						// count contacts
						if(!LocalDataManager.getGotIT(countContacts)){
							lastTrophies = true;
							ContentManager.trophyCountContacts(nSMS);
						}
						
						// count SMS
						if(!LocalDataManager.getGotIT(countSMS)){
							lastTrophies = true;
							ContentManager.trophyCountSMS(nContacts);
						}
						
						Thread.sleep(WAIT-WAIT_OFFSET);		// slow down service
					
					// stop thread
					}else{
						runThread = false;
						stopSelf();
					}
					
				} catch (InterruptedException e) {
					Log.v("TrophyService", "Sleep interrupted.");
				}
			}
		}
	}


	@Override
	public void onDestroy(){
		runThread = false;
		super.onDestroy();
		
	}


	@Override
	public IBinder onBind(Intent intent) {
		//Do nothing
		return null;
	}

}
